package com.example.mapper;

import com.example.pojo.Seat;
import com.example.pojo.Ticket;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface TicketMapper {

    @Insert("insert into ticket(order_num, trade_no,userID,eventID,seatID,ticket_price,status,create_time)" +
            "values(#{orderNum},#{tradeNo},#{userID},#{eventID},#{seatID},#{ticketPrice},#{status},#{createTime})")
    void save(Ticket ticket);

    @Delete("delete from ticket where ticket.ticketID = #{ticketID}")
    void delete(Integer ticketID);

    List<Ticket> list(Integer userID, Integer eventID, Integer ticketID);

    List<Ticket> listAll(Integer userID, Integer eventID, Integer ticketID,String status, Integer startIdx, Integer pageSize);
    long listAllCount(Integer userID, Integer eventID, Integer ticketID, String status, Integer startIdx, Integer pageSize);

    @Update("update ticket set status=#{status}, trade_no = #{tradeNo} where order_num=#{orderNum}")
    int updateStatus(String orderNum,String tradeNo, String status);

    @Select({"<script>",
            " select ",
            " count(ticketID) ",
            " FROM ticket WHERE eventID = #{eventID} and status in ('待支付', '生效', '失效') and seatID in ",
            "<foreach item='item' index='index' collection='seatIDs' open='(' separator=',' close=')'>",
            "#{item}",
            "</foreach>",
            "</script>"})
    int selectSeatIsSold(Integer eventID, List<Integer> seatIDs);

    @Select("select * from ticket where ticketID = #{ticketID}")
    Ticket selectById(Integer ticketID);

    @Select("select u.phone_number from ticket t left join user u on t.userID = u.userID where t.order_num=#{orderNum}" +
            "limit 1")
    String selectUserPhoneNumberByOrderNum(String orderNum);

    @Select("select * from ticket where order_num=#{orderNum}")
    List<Ticket> selectTicketsByOrderNum(String orderNum);

    //最后的折线图接口
    @Select("SELECT DATE_FORMAT(create_time, '%Y-%m-%d' ) days, count(*) count\n" +
            "FROM ( SELECT * FROM ticket WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date(create_time) ) as t,seat as s\n" +
            "where t.eventID=#{eventID} and t.seatID = s.id and s.seat_type=#{seatType} and t.status='生效'\n" +
            "GROUP BY days")
    List<Map<String,Object>> brokenLineGraphList(Integer eventID,Integer seatType);
}
